#!/usr/bin/env bash
sudo apt-get install libncurses5
read -p "Please input mysql root password" mysqlrootpwd
wget -c https://downloads.mysql.com/archives/get/p/23/file/mysql-5.6.51-linux-glibc2.12-x86_64.tar.gz
tar zxvf mysql-5.6.51-linux-glibc2.12-x86_64.tar.gz
mv mysql-5.6.51-linux-glibc2.12-x86_64 /usr/local/mysql
cat > /etc/my.cnf<<EOF
[client]
default-character-set=utf8mb4
[mysqld]
basedir=/usr/local/mysql
datadir=/usr/local/mysql/data
character-set-server=utf8mb4
collation-server=utf8mb4_general_ci
innodb_large_prefix = ON
innodb_file_format = Barracuda
innodb_file_per_table = ON
[mysql]
default-character-set=utf8mb4
EOF


groupadd mysql
useradd -s /sbin/nologin -M -g mysql mysql
chown -R mysql:mysql /usr/local/mysql/
ln -s /usr/lib/x86_64-linux-gnu/libncurses.so.6.2 /usr/lib/x86_64-linux-gnu/libncurses.so.5

/usr/local/mysql/scripts/mysql_install_db --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --user=mysql
# 5.7 以后才用得到这个 /usr/local/mysql/bin/mysqld --initialize-insecure --user=mysql --basedir=/usr/local/mysql  --datadir=/usr/local/mysql/data
/usr/local/mysql/support-files/mysql.server start
/usr/local/mysql/support-files/mysql.server stop
cat > /usr/lib/systemd/system/mysql.service<<EOF
[Unit]
Description=MySQL Community Server
After=network.target
After=syslog.target

[Install]
WantedBy=multi-user.target
Alias=mysql.service

[Service]
User=mysql
Group=mysql

# Execute pre and post scripts as root
PermissionsStartOnly=true

# Needed to create system tables etc.
#ExecStartPre=/usr/bin/mysql-systemd-start pre

# Start main service
ExecStart=/usr/local/mysql/bin/mysqld --defaults-file=/etc/my.cnf

# Don't signal startup success before a ping works
#ExecStartPost=/usr/bin/mysql-systemd-start post

# Give up if ping don't get an answer
TimeoutSec=600
Restart=always
PrivateTmp=false
EOF
systemctl daemon-reload
systemctl enable mysql
systemctl start mysql

ln -s /usr/local/mysql/bin/mysql* /usr/bin

cat > /tmp/mysql_sec_script<<EOF
use mysql;
update user set password=password('$mysqlrootpwd') where user='root';
delete from user where not (user='root') ;
delete from user where user='root' and password='';
drop database test;
DROP USER ''@'%';
flush privileges;
EOF

/usr/local/mysql/bin/mysql -u root < /tmp/mysql_sec_script

rm -f /tmp/mysql_sec_script

echo "DONE!"

